package com.ziyun.pop.mall.module.oss.core;

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
//import com.baomidou.mybatisplus.extension.api.Assert;
import com.utility.DateUtils;

import net.sf.json.JSONObject;

//import org.junit.Assert;

/**
 * OSS 加签 回调处理
 * 
 * @author zh
 * @date 2018/5/1017:08
 */
@Controller
@PropertySource("")
public class OssHandle {

	@Value("${oss.endpoint}")
	private String endpoint;

	@Value("${oss.bucketName}")
	private String bucketName;

	@Value("${oss.picLocation}")
	private String picLocation;

	@Value("${oss.accessKeyId}")
	private String accessKeyId;

	@Value("${oss.accessKeySecret}")
	private String accessKeySecret;

	@Value("${oss.host}")
	private String host;

	@Value("${oss.callbackUrl}")
	private String callbackUrl;

	/**
	 * 获取ｏｓｓ 验签
	 * 
	 * @param request
	 * @param response
	 */
	@GetMapping("/oss/getSignature")
	@ResponseBody
	public void getSignature(HttpServletRequest request, HttpServletResponse response) {
		String dir = request.getParameter("dir");
		String ori_filename = request.getParameter("ori_filename");
		String fileType = null;
		if (StringUtils.isNotEmpty(ori_filename)) {
			fileType = ori_filename.substring(ori_filename.lastIndexOf("."));
		}

		String newFileName = System.currentTimeMillis() + fileType;
		dir += newFileName;

		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			long expireTime = 30;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
			Date expiration = new Date(expireEndTime);
			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

			String postPolicy = client.generatePostPolicy(expiration, policyConds);
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);

			Map<String, String> respMap = new LinkedHashMap<String, String>();
			respMap.put("accessid", accessKeyId);
			respMap.put("policy", encodedPolicy);
			respMap.put("signature", postSignature);
			// respMap.put("expire", formatISO8601Date(expiration));
			respMap.put("dir", dir);
			respMap.put("newFileName", newFileName);
			respMap.put("ori_filename", ori_filename);
			respMap.put("host", host);
			respMap.put("callback_var", new JSONObject().toString());
			respMap.put("expire", String.valueOf(expireEndTime / 1000));

			JSONObject callBackParams = new JSONObject();
			callBackParams.put("callbackUrl", callbackUrl);
			callBackParams.put("callbackBody", "oldFilename='" + ori_filename
					+ "'&filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
			callBackParams.put("callbackBodyType", "application/x-www-form-urlencoded");
			respMap.put("callback", BinaryUtil.toBase64String(callBackParams.toString().getBytes("utf-8")));

			JSONObject jaRS = JSONObject.fromObject(respMap);
			// 返回值
			System.out.println(respMap);
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Allow-Methods", "GET, POST");
			response.getWriter().println(jaRS);
			response.setStatus(HttpServletResponse.SC_OK);
			response.flushBuffer();

		} catch (Exception e) {
			e.printStackTrace();
//			Assert.fail(e.getMessage());
		}

	}

	/**
	 * 获取ｏｓｓ 验签
	 * 
	 * @param request
	 * @param response
	 */
	@GetMapping("/oss/getSignatureNew")
	@ResponseBody
	public void getSignatureNew(HttpServletRequest request, HttpServletResponse response) {
		String dir = request.getParameter("dir");
		String ori_filename = request.getParameter("ori_filename");
		String fileType = null;
		if (StringUtils.isNotEmpty(ori_filename)) {
			fileType = ori_filename.substring(ori_filename.lastIndexOf("."));
		}

		String newFileName = System.currentTimeMillis() + fileType;
		// dir += newFileName;

		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			long expireTime = 30;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
			Date expiration = new Date(expireEndTime);
			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

			String postPolicy = client.generatePostPolicy(expiration, policyConds);
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);

			Map<String, String> respMap = new LinkedHashMap<String, String>();
			respMap.put("accessid", accessKeyId);
			respMap.put("policy", encodedPolicy);
			respMap.put("signature", postSignature);
			// respMap.put("expire", formatISO8601Date(expiration));
			respMap.put("dir", dir);
			respMap.put("newFileName", newFileName);
			respMap.put("ori_filename", ori_filename);
			respMap.put("host", host);
			respMap.put("expire", String.valueOf(expireEndTime / 1000));
			respMap.put("callback_var", new JSONObject().toString());

			JSONObject callBackParams = new JSONObject();
			callBackParams.put("callbackUrl", callbackUrl);
			callBackParams.put("callbackBody", "oldFilename='" + ori_filename + "'&date='"
					+ DateUtils.format(new Date(), DateUtils.PATTERN_DATE_TIME)
					+ "'&filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
			callBackParams.put("callbackBodyType", "application/x-www-form-urlencoded");
			respMap.put("callback", BinaryUtil.toBase64String(callBackParams.toString().getBytes("utf-8")));

			JSONObject jaRS = JSONObject.fromObject(respMap);
			// 返回值
			System.out.println(respMap);
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Allow-Methods", "GET, POST");
			response.getWriter().println(jaRS);
			response.setStatus(HttpServletResponse.SC_OK);
			response.flushBuffer();

		} catch (Exception e) {
			e.printStackTrace();
			// Assert.fail(e.getMessage());
		}

	}

	/**
	 * oss 回调
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("oss/ossCallback")
	@ResponseBody
	public void ossCallback(HttpServletRequest request, HttpServletResponse response) throws IOException {

		// todo 此处需要 判断是否为oss请求
		Enumeration paramNames = request.getParameterNames();
		Map<String, String> respMap = new LinkedHashMap<String, String>();
		while (paramNames.hasMoreElements()) {// 遍历取出所有参数
			String name = paramNames.nextElement().toString();
			respMap.put(name, request.getParameter(name));
		}
		respMap.put("Status", "OK");

		// 返回状态给OSS
		response.getWriter().println(JSONObject.fromObject(respMap).toString());
		response.setStatus(HttpServletResponse.SC_OK);
		response.flushBuffer();

	}

}
